package com.cos.config.thread.task;

import com.cos.config.cons.ConstantAttribute;
import com.qcloud.cos.transfer.Transfer;
import com.qcloud.cos.transfer.TransferProgress;

/**
 * @author Irving
 * @create 2021/7/16
 * @desc 上传和下载的公用进度类, 该类使用子线程调用
 **/
public class UDTransferProgress implements Runnable {

      /**
       * 传输对象,包含下载或者上传的进度
       */
      private final Transfer transfer;

      public UDTransferProgress(Transfer transfer) {
            this.transfer = transfer;
      }

      @Override
      public void run() {
            //循环终止条件:当文件传输失败时
            do {
                  try {
                        Thread.sleep(ConstantAttribute.COS_REFRESH_PROGRESS_MILLIS);
                  } catch (InterruptedException e) {
                        return;
                  }
                  TransferProgress progress = transfer.getProgress();
                  //已经上传的字节
                  long soFar = progress.getBytesTransferred();
                  //总字节
                  long total = progress.getTotalBytesToTransfer();
                  //传输的百分比进度
                  double pct = progress.getPercentTransferred();
                  //剩余没有上传的字节
                  long remaining = total - soFar;
                  System.out.printf("正在执行---->[已进行:%dM 剩余:%dM 总:%dM] = %.02f%%\n", soFar / 1024 / 1024, remaining / 1024 / 1024, total / 1024 / 1024, pct);
            } while (!transfer.isDone());
      }
}
